package com.yocard.yxyd.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yocard.yxyd.http.model.request.CsmListRequest;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;
import com.yocard.yxyd.R;
import com.yocard.yxyd.adapter.OrderListAdapter;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.http.model.request.OrderListRequest;
import com.yocard.yxyd.http.model.response.OrderListBean;
import com.yocard.yxyd.others.ClassicsHeader;
import com.yocard.yxyd.ui.activity.OrderDetailActivity;
import com.yocard.yxyd.ui.contract.OrderListContract;
import com.yocard.yxyd.ui.fragment.base.BaseFragment;
import com.yocard.yxyd.ui.presenter.OrderListPresenter;
import com.yocard.yxyd.utils.CommonUtils;
import com.yocard.yxyd.utils.util.SizeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.yocard.yxyd.event.EventCode.REFRESH_BANNER;
import static com.yocard.yxyd.event.EventCode.REFRESH_ORDER_LIST;

/**
 * Created on 2019/4/3.
 */
public class OrderListFragment extends BaseFragment<OrderListPresenter> implements OrderListContract.View {

    @BindView(R.id.empty_view)
    RelativeLayout emptyView;
    @BindView(R.id.recycle_view)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.refresh_header)
    ClassicsHeader classicsHeader;
    @BindView(R.id.tv_tip)
    TextView tvTip;

    private ValueCallback<Integer> callback;

    private String loanType;

    private int currentPage = 1;
    List<OrderListBean.OrderList> datas = new ArrayList<>();
    protected OrderListAdapter mAdapter;
    private OrderListRequest orderListRequest;
    protected OrderFragment parentFragment;

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ft_order_list;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        classicsHeader.setCallback(callback);
    }

    @Override
    protected void initEventAndData() {
        parentFragment = ((OrderFragment) OrderListFragment.this.getParentFragment());
        mAdapter = new OrderListAdapter(datas);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.shape_transparent));
        recyclerView.addItemDecoration(dividerItemDecoration);

        refreshLayout.setOnRefreshListener(refreshLayout1 -> {
            MobclickAgent.onEvent(mContext,"5","refresh_order_list");
            currentPage = 1;
//            orderListRequest.setPage(currentPage);
            orderListRequest.setLoan_type(loanType);
            orderListRequest.setCity_code(parentFragment.getCurrentCityCode());
            mPresenter.fetchOrderList(currentPage, orderListRequest);
            EventBus.getDefault().post(new CommonBean(REFRESH_BANNER));
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout1 -> {
            MobclickAgent.onEvent(mContext,"6","loadmore_order_list");
            currentPage++;
//            orderListRequest.setPage(currentPage);
            orderListRequest.setLoan_type(loanType);
            orderListRequest.setCity_code(parentFragment.getCurrentCityCode());
            mPresenter.fetchOrderList(currentPage, orderListRequest);
        });

        parentFragment.setSelectCallback(new ValueCallback<OrderListRequest>() {
            @Override
            public void onReceiveValue(OrderListRequest value) {
                if(value == null) {
                    orderListRequest = new OrderListRequest();
                    return;
                }
                parentFragment.setIcoSelect(!CommonUtils.checkObjAllFieldsIsNull(value));
                recyclerView.scrollToPosition(0);
                ((OrderFragment) OrderListFragment.this.getParentFragment()).closeDrawer();
                orderListRequest = (OrderListRequest) value.clone();
                currentPage = 1;
//                orderListRequest.setPage(currentPage);
                orderListRequest.setLoan_type(loanType);
                orderListRequest.setCity_code(parentFragment.getCurrentCityCode());
                showLoadingDialog();
                mPresenter.fetchOrderList(currentPage, orderListRequest);
            }
        });

        showLoadingDialog();
        orderListRequest = new OrderListRequest(currentPage, loanType);
        orderListRequest.setCity_code(parentFragment.getCurrentCityCode());
        mPresenter.fetchOrderList(currentPage, orderListRequest);

        parentFragment.setLocationListener(value -> {
            currentPage = 1;
//            orderListRequest.setPage(currentPage);
            orderListRequest.setCity_code(value);
            showLoadingDialog();
            mPresenter.fetchOrderList(currentPage, orderListRequest);
        });

        mAdapter.setOnItemClickListener(value -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable("data",value);
            ActivityUtils.startActivity(bundle,OrderDetailActivity.class);
        });
    }

    public void setRefreshCallbacl(ValueCallback<Integer> callback) {
        this.callback = callback;
        if(classicsHeader != null){
            classicsHeader.setCallback(callback);
        }
    }

    public void setViewPagePos(int viewPagePos) {
        switch (viewPagePos) {
            case 1:
                loanType = "xinyong";
                break;
            case 2:
                loanType = "diya";
                break;
            case 3:
                loanType = "chezhu";
                break;
            case 4:
                loanType = "zhuangxiu";
                break;
            case 5:
                loanType = "bank";
                break;
        }
    }

    @Override
    public void OnfetchOrderList(List<OrderListBean.OrderList> list) {
        if (currentPage == 1) {
            datas.clear();
            if (list.size() == 0) {
                if(parentFragment.getIcoSelectStatus()){
                    tvTip.setText(getString(R.string.no_result));
                }else {
                    tvTip.setText(getString(R.string.empty_order_list));
                }

                showEmptyView(emptyView);
            } else {
                hiddenEmptyView(emptyView);
                datas.addAll(list);
            }
            refreshLayout.finishRefresh();
//            refreshLayout.resetNoMoreData();
            mAdapter.notifyDataSetChanged();
            dismisDialog();
        } else {
            datas.addAll(list);
            refreshLayout.finishLoadMore();
        }
        if (list.size() < Constants.PAGE_SIZE) {
            refreshLayout.finishLoadMoreWithNoMoreData();
        }
        mAdapter.notifyDataSetChanged();
    }

    protected void showEmptyView(View view) {
        LinearLayout linearLayout = view.findViewById(R.id.ll_empty_view);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) linearLayout.getLayoutParams();
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        layoutParams.topMargin = SizeUtils.dp2px(74);
        linearLayout.setLayoutParams(layoutParams);
        view.setVisibility(View.VISIBLE);
    }

    @Override
    public void showErrorMsg(String msg) {
        super.showErrorMsg(msg);
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
//        if(datas.size() > 0) {
//            return;
//        }
        //清楚列表数据
        datas.clear();
        mAdapter.notifyDataSetChanged();
//        if(currentPage == 1){
//            showEmptyView(emptyView);
//            tvTip.setText(getString(R.string.empty_order_list));
//        }
        showEmptyView(emptyView);
        tvTip.setText(getString(R.string.empty_order_list));
    }

    public void scrollTop(){
        recyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onEvent(mContext,"4","show_order_list");
    }

    public void refresh(){//提供给父fragment刷新
        recyclerView.scrollToPosition(0);
        refreshLayout.autoRefresh();
    }
}
